/**
 * @author[wengcj]
 * @version[创建日期，2021/11/2 9:55]
 * @function[功能简介 ]
 **/
package com.example.myapplication;

import android.Manifest
import android.app.Instrumentation
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.LinearLayout
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity

class FirstAct : AppCompatActivity() {

    //默认写法
//    override fun onCreate(savedInstanceState: Bundle?) {
//        super.onCreate(savedInstanceState)
//        val firstButton = Button(this)
//        firstButton.text = "first"
//        firstButton.setOnClickListener {
//            startActivityForResult(Intent(this,SecondAct::class.java),1001)
//        }
//        val linearLayout = LinearLayout(this)
//        linearLayout .addView(firstButton)
//        setContentView(linearLayout)
//    }
//
//    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
//        super.onActivityResult(requestCode, resultCode, data)
//        if (data != null){
//            Toast.makeText(this,data.getStringExtra("data"), Toast.LENGTH_SHORT).show()
//        }
//    }

    //新写法
    private val requestDataLauncher =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == RESULT_OK) {
                val data = result.data?.getStringExtra("data")
                // Handle data from SecondActivity
                Toast.makeText(this, data, Toast.LENGTH_SHORT).show()
            }
        }

    private val requestPermissionLauncher =
        registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
            Toast.makeText(this, "granted$granted", Toast.LENGTH_SHORT).show()
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //启动界面
        val firstStartActButton = Button(this)
        firstStartActButton.text = "first StartAct"
        firstStartActButton.setOnClickListener {
            val intent = Intent(this, SecondAct::class.java)
            requestDataLauncher.launch(intent)
        }

        //请求权限s
        val firstRequestPermissionButton = Button(this)
        firstRequestPermissionButton.text = "first RequestPermission"
        firstRequestPermissionButton.setOnClickListener {
            requestPermissionLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE)
        }

        val linearLayout = LinearLayout(this)
        linearLayout.orientation = LinearLayout.VERTICAL
        linearLayout.addView(firstStartActButton)
        linearLayout.addView(firstRequestPermissionButton)
        setContentView(linearLayout)
    }
}